package com.gzw.shop.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.gzw.shop.R;
import com.gzw.shop.utils.ToastUtils;
import com.gzw.shop.widget.ClearEditText;
import com.gzw.shop.widget.GToolbar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;
import cn.smssdk.utils.SMSLog;

public class RegActivity extends BaseActivity {

    // 默认使用中国区号
    private static final String DEFAULT_COUNTRY_ID = "42";

    @BindView(R.id.toolbar)
    GToolbar toolbar;
    @BindView(R.id.txtCountry)
    TextView txtCountry;
    @BindView(R.id.txtCountryCode)
    TextView txtCountryCode;
    @BindView(R.id.edittxt_phone)
    ClearEditText edittxtPhone;
    @BindView(R.id.edittxt_pwd)
    ClearEditText edittxtPwd;

    EventHandler handler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_reg;
    }

    @Override
    public void initView() {
        toolbar.setRightBtnOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCode();
            }
        });

        toolbar.setIvLeftOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void initData() {

        //1.初始化SDK
        SMSSDK.initSDK(this, "1da1aa6484568", "9ce9367ab2e3b01700c8f08ce046a7cb");

        //2.注册回调接口
        handler = new EventHandler() {
            @Override
            public void afterEvent(final int event, final int result, final Object data) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (result == SMSSDK.RESULT_COMPLETE) {
                            //回调完成
                            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                                //提交验证码成功
                            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                                //获取验证码成功 跳转到下一页面
                                afterVerificationCodeRequested((Boolean) data);

                            } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                                //返回支持发送验证码的国家列表
                            }
                        } else {
                            // 根据服务器返回的网络错误，给toast提示
                            try {
                                ((Throwable) data).printStackTrace();
                                Throwable throwable = (Throwable) data;

                                JSONObject object = new JSONObject(
                                        throwable.getMessage());
                                String des = object.optString("detail");
                                if (!TextUtils.isEmpty(des)) {
                                    ToastUtils.show(RegActivity.this, des);
                                    return;
                                }
                            } catch (Exception e) {
                                SMSLog.getInstance().w(e);
                            }
                        }

                    }
                });
            }
        };

        SMSSDK.registerEventHandler(handler);

        //获取国家编码和名称
        String[] country = SMSSDK.getCountry(DEFAULT_COUNTRY_ID);
        if (country != null) {
            txtCountryCode.setText("+" + country[1]);
            txtCountry.setText(country[0]);
        }
    }

    //获取验证码
    private void getCode() {

        String phone = edittxtPhone.getText().toString().trim().replaceAll("\\s*", "");
        String code = txtCountryCode.getText().toString().trim();

        checkPhoneNum(phone, code);

        //not 86   +86
        SMSSDK.getVerificationCode(code, phone);

    }


    /**
     * 校验手机号格式是否正确
     *
     * @param phone
     * @param code
     */
    private void checkPhoneNum(String phone, String code) {
        if (code.startsWith("+")) {
            code = code.substring(1);
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.show(this, "请输入手机号码");
            return;
        }

        if (code == "86") {
            if (phone.length() != 11) {
                ToastUtils.show(this, "手机号码长度不对");
                return;
            }

        }

        String rule = "^1(3|5|7|8|4)\\d{9}";
        Pattern p = Pattern.compile(rule);
        Matcher m = p.matcher(phone);

        if (!m.matches()) {
            ToastUtils.show(this, "您输入的手机号码格式不正确");
            return;
        }

    }


    /**
     * 请求验证码后跳转到验证码填写页面
     *
     * @param smart
     */
    private void afterVerificationCodeRequested(boolean smart) {


        String phone = edittxtPhone.getText().toString().trim().replaceAll("\\s*", "");
        String code = txtCountryCode.getText().toString().trim();
        String pwd = edittxtPwd.getText().toString().trim();

        if (code.startsWith("+")) {
            code = code.substring(1);
        }

        Intent intent = new Intent(this, RegSecondActivity.class);
        intent.putExtra("phone", phone);
        intent.putExtra("pwd", pwd);
        intent.putExtra("countryCode", code);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(handler);
    }
}
